package middleware

import (
	"chat_08_21/constn"
	"chat_08_21/global"
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"log"
	"net/http"
)

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.GetHeader("x-token")

		type MyCustomClaims struct {
			Foo uint32 `json:"foo"`
			jwt.RegisteredClaims
		}

		token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (any, error) {
			return []byte(constn.KEY_JWT), nil
		})
		if err != nil {
			log.Fatal(err)
		} else if claims, ok := token.Claims.(*MyCustomClaims); ok {
			fmt.Println(claims.Foo, claims.Issuer)
		} else {
			log.Fatal("unknown claims type, cannot proceed")
		}

		get := global.RDB.Get(context.Background(), fmt.Sprintf("token:%d", token.Claims.(*MyCustomClaims).Foo))

		if get.Val() != tokenString {
			c.JSON(http.StatusOK, gin.H{
				"code":    100000,
				"message": "登录失效",
				"data":    "",
			})
			c.Abort()
			return
		}

		c.Set("user_id", token.Claims.(*MyCustomClaims).Foo)

		c.Next()

	}
}
